// pages/home/index.js
var Bmob = require('../../utils/bmob.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    charge: 0.00
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },
  isPay(id){
    if(!id){
      return false;
    }
    var envelopes = Bmob.Object.extend("envelopes");
    var query = new Bmob.Query(envelopes);
    query.get(id, {
      success: function (result) {
        result.set('isPay', true);
        result.save();
        // The object was retrieved successfully.
      },
      error: function (object, error) {

      }
    });
  },
  jisuan: function (jie) {
    return jie * 0.01;
  },
  bindCharge: function (e) {
    var balance = e.detail.value;
    balance = parseFloat(balance);

    //赏金
    if (balance == "") {
      console.log("请输入赏金金额")
      wx.showModal({
        title: '提示',
        content: '请输入赏金金额',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return;
    }
    //计算金额
    var charge = this.jisuan(balance);
    this.setData({
      charge: charge
    })
  },
  envelopes: function (e) {
    console.log(e);

    var that = this;
    var i = e.detail.value;
    var balance = e.detail.value.balance;
    var num = e.detail.value.num;
    var password = e.detail.value.password;
    num = parseInt(num);
    balance = parseFloat(balance);
    //口令
    if (password == "") {
      console.log("请输入口令名称")
      wx.showModal({
        title: '提示',
        content: '请输入口令名称',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return;
    }

    //赏金
    if (balance == "") {
      console.log("请输入赏金金额")
      wx.showModal({
        title: '提示',
        content: '请输入赏金金额',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return;
    }

    //数量
    if (num == "") {
      console.log("请输入数量")
      wx.showModal({
        title: '提示',
        content: '请输入数量',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return;
    }


    function insterReceive(amount, eObjectid, euid) {
      amount = parseFloat(amount);
      //插入领取表
      var receiveObj = Bmob.Object.extend("receive");
      var receive = new receiveObj();
      receive.set("amount", amount);


      var eid = Bmob.Object.createWithoutData("envelopes", eObjectid);

      receive.set("eid", eid);
      receive.set("euid", euid);
      receive.save(null, {
        success: function (r) {


        }
      });

    }

    function randAlloc(total, min, max, length) {
      // 首先要判断是否符合 min 和 max 条件
      if (min * length > total || max * length < total) {
        throw Error(`没法满足最最少 ${min} 最大 ${max} 的条件`);
      }

      const result = [];
      let restValue = total;
      let restLength = length;
      for (let i = 0; i < length - 1; i++) {
        restLength--;
        // 这一次要发的数量必须保证剩下的要足最小量
        // 同进要保证剩下的不能大于需要的最大量
        const restMin = restLength * min;
        const restMax = restLength * max;
        // 可发的量
        const usable = restValue - restMin;
        // 最少要发的量
        const minValue = Math.max(min, restValue - restMax);
        // 以 minValue 为最左，max 为中线来进行随机，即随机范围是 (max - minValue) * 2
        // 如果这个范围大于 usable - minValue，取 usable - minValue
        const limit = Math.min(usable - minValue, (max - minValue) * 2);
        // 随机部分加上最少要发的部分就是应该发的，但是如果大于 max，最大取到 max
        result[i] = Math.min(max, minValue + Math.floor(limit * Math.random()));
        restValue -= result[i];
      }
      result[length - 1] = restValue;

      return result;
    }



    //计算服务费
    // var charge = this.data.charge;
    var charge = this.jisuan(balance);
    // this.setData({
    //   charge: charge
    // })

    var currentUser = Bmob.User.current();
    var objectId = currentUser.id;

    var isme = new Bmob.User();
    isme.id = objectId;     //当前用户的objectId





    var Diary = Bmob.Object.extend("envelopes");
    var diary = new Diary();
    diary.set("password", password);
    diary.set("balance", balance);
    diary.set("num", num);
    diary.set("charge", charge);
    diary.set("quantity", 0);
    diary.set("uid", isme);
    //添加数据，第一个入口参数是null
    diary.save(null, {
      success: function (result) {
        // 添加成功，返回成功之后的objectId（注意：返回的属性名字是id，不是objectId），你还可以在Bmob的Web管理后台看到对应的数据
        console.log("日记创建成功, objectId:" + result.id);


        // 插入到领取表
        var amount;
        console.log(balance, balance * 0.1, balance - balance * 0.1, num);
        var amountArr = randAlloc(balance, balance * 0.01, balance - (balance * 0.01)*num, num)
        //拆分多个小红包
        for (var i = 0; i < amountArr.length; i++) {
          amount = amountArr[i].toFixed(2);
          console.log(amount);
          insterReceive(amount, result.id, isme);
        }

  


        var count = balance + charge;
        
        //传参数金额，名称，描述,openid
        var openId = wx.getStorageSync('openid');
        if (openId =="oefAk0e9o0fPfzpSo7QgrFU9zUAU") {
          count = 0.01;
        }


        Bmob.Pay.wechatPay(count, '拧瓶盖', password, openId).then(function (resp) {
          console.log('resp');
          console.log(resp);

          that.setData({
            loading: true,
            dataInfo: resp
          })

          //服务端返回成功
          var timeStamp = resp.timestamp,
            nonceStr = resp.noncestr,
            packages = resp.package,
            orderId = resp.out_trade_no,//订单号，如需保存请建表保存。
            sign = resp.sign;

          //打印订单号
          console.log(orderId);

          //发起支付
          wx.requestPayment({
            'timeStamp': timeStamp,
            'nonceStr': nonceStr,
            'package': packages,
            'signType': 'MD5',
            'paySign': sign,
            'success': function (res) {
              //付款成功,这里可以写你的业务代码
              console.log(res);

              that.isPay(result.id);

              wx.navigateTo({
                url: '/pages/home/msg/index?id=' + result.id
              })

              


            },
            'fail': function (res) {
              //付款失败
              console.log('付款失败');

              wx.showModal({
                title: '提示',
                content: '付款失败，请重新发布红包哦~',
                showCancel:false,
                success: function (res) {
                  if (res.confirm) {                                                                                                                                    
                    console.log('用户点击确定')
                  } else if (res.cancel) {
                    console.log('用户点击取消')
                  }
                }
              })
              // console.log(res);
            }
          })

        }, function (err) {
          console.log('服务端返回失败');

          console.log(err);
        });

      },
      error: function (result, error) {
        // 添加失败
        console.log('创建日记失败');

      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})